package dpss.commons;

import java.io.IOException;
import java.util.Date;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * A singleton logging class to be used globally in the project
 * @author musab.mirza
 *
 */
public class CustomLogger {
	
	// The path to the log file
	private static String LOG_FILE_PATH = "log.log";

	private static CustomLogger customLogger = new CustomLogger();
	private static Logger logger = Logger.getLogger("mylogger");
	private static FileHandler fh = null;
	private boolean logToConsole;

	private CustomLogger() {
		logToConsole = false;
	}

	/**
	 * Returns the instance of this logger
	 * 
	 * @return
	 */
	public static CustomLogger getInstance() {
		if (fh == null) {
			setupLogger();
		}
		return customLogger;
	}
	
	public static void changeLogFile(String logFileName){
		logger.removeHandler(fh);
		fh.close();
		try {
			fh = new FileHandler(logFileName, true);
			fh.setFormatter(new LogFormatter());
			logger.addHandler(fh);
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	

	/**
	 * Sets up the logger and associates the file
	 */
	private static void setupLogger(){
		try {
			fh = new FileHandler(LOG_FILE_PATH, true);
			fh.setFormatter(new LogFormatter());
			logger.addHandler(fh);
			
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		logger.setUseParentHandlers(false);
	}
		

	/**
	 * Logs (appends) a message to the log file
	 * 
	 * @param message
	 */
	public void log(String message) {
		logger.log(Level.OFF, message);
		if (logToConsole){
			Date d = new Date();
			System.out.println(d.toString() + ": " + message );
		}
	}
	
	/**
	 * Outputs to the console
	 * @param message
	 */
	public void out(String message){
		System.out.println(message);
	}
	
	/**
	 * A simple way to add several lines to the console
	 * in order to create a cls effect like in windows
	 * cms
	 */
	public void cls(){
		System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
	}

	/**
	 * Always log to console
	 */
	public void logConsole(boolean b) {
		logToConsole = b;
	}
}
